package leo.game.ui
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	
	import leo.TDGame;
	import leo.data.BuildMap;
	import leo.data.GameConfig;
	import leo.data.GameConst;
	import leo.data.GameModel;
	import leo.data.MonsterVO;
	import leo.data.TowerVO;
	import leo.game.display.BaseMonster;
	import leo.game.display.BaseTower;
	import leo.game.display.Bullet;
	import leo.game.display.MapObject;
	import leo.game.stage.Game;
	import leo.manager.BitmapManager;
	import leo.manager.McMannager;
	import leo.manager.MonsterManager;
	import leo.manager.VOManager;
	import leo.util.GameUtil;
	
	public class UIMap extends Sprite
	{
		private static var _instance :UIMap = null;

		/**
		 * 是否新建造新防守塔 
		 */		
		public var isAddNewTower :Boolean = false;
		/**
		 * 正常寻路路径 
		 */		
		public var path :Array;
		/**
		 * 对比路径 
		 */		
		public var contrastPath :Array;
		/**
		 * 对比地图数组 
		 */		
		public var contrastMapAry :Array;
		/**
		 * 是否能建造 
		 */		
		public var canBuild :Boolean = true;
		/**
		 * 防守塔的攻击范围 
		 */		
		public var towerAttackRange :TowerAttackRange;
		/**
		 * 是否是拆除
		 */		
		public var isRemove :Boolean = false;
		/**
		 * 是否是移动
		 */		
		public var isMove :Boolean = false;
		/**
		 * 鼠标上的防守塔对象 
		 */		
		public var dragTower :BaseTower = null;
		/**
		 * 路径层 
		 */		
		private var pathLayer :Shape;
		/**
		 * 底图 
		 */		
		private var map :MovieClip;
		/**
		 * 当前关卡的地图数据 
		 */		
		private var curMapAry :Array;
		/**
		 * 临时X值 
		 */		
		private var tempX :int;
		/**
		 * 临时Y值 
		 */		
		private var tempY :int;
		/**
		 * 地图上的防守塔 
		 */		
		private var towerList :Vector.<BaseTower>;
		/**
		 * 地图上的怪物 
		 */		
		private var monsterList :Vector.<BaseMonster>;
		/**
		 * 当前地图的起点 
		 */		
		private var curMapStartPoint :Point;
		/**
		 * 当前地图的终点 
		 */		
		private var curMapEndPoint :Point;
		/**
		 * 防守塔吸附 
		 */		
		private var adsorber :BuildRect;
		/**
		 * 地图网格 
		 */		
		private var mapGrid :MapGrid;
		/**
		 * 鼠标上的对象 
		 */		
		private var theMouseOn :BaseTower
		public function UIMap()
		{
			super();
		}
		
		public function init(level :int = 0):void
		{
			this.towerList = GameModel.instance.towerList;
			GameModel.instance.curLevel = level;
			if(this.map)
			{
				this.removeChild(this.map);
				this.map = null;
			}
			var name :String = GameConfig.map_name_ary[level];
			var mc :MovieClip = McMannager.instance.getMCByName(name);
			this.map = mc;
			this.addChildAt(mc,0);
			
			if(this.adsorber)
			{
				this.removeChild(this.adsorber);
				this.adsorber = null;
			}
			this.adsorber = new BuildRect();
			this.addChild(adsorber);
			this.adsorber.visible = false;
			
			if(this.pathLayer)
			{
				this.removeChild(this.pathLayer);
				this.pathLayer = null;
			}
			this.pathLayer = new Shape();
			this.addChild(this.pathLayer);
			
			removeTowerAttRange();
			this.towerAttackRange = new TowerAttackRange();
			this.towerAttackRange.hideRange();
			this.addChild(towerAttackRange);
			
			if(GameConfig.is_show_grid)
			{
				
				if(this.mapGrid)
				{
					this.removeChild(this.mapGrid);
					this.mapGrid = null;
				}
				this.mapGrid = new MapGrid();
				this.addChild(this.mapGrid);
			}
			
			BuildMap.instance.init();
			this.curMapAry = GameModel.instance.curMapAry;
			
			this.curMapStartPoint = GameConfig.m_start_point_ary[level];
			this.curMapEndPoint = GameConfig.m_end_point_ary[level];
			this.path = BuildMap.instance.findPath(curMapStartPoint,curMapEndPoint,this.curMapAry);
			
			addEventListener(MouseEvent.MOUSE_DOWN,mouseHandler);
			addEventListener(MouseEvent.MOUSE_UP,mouseHandler);
			addEventListener(MouseEvent.MOUSE_OVER,mouseHandler);
			addEventListener(MouseEvent.MOUSE_OUT,mouseHandler);
			addEventListener(MouseEvent.CLICK,mouseHandler);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseHandler);
		}
		
		

		/**
		 * 增加新防守塔到鼠标上 
		 * @param name
		 * 
		 */		
		public function addNewTower(name :String):void
		{
			if(isAddNewTower)
			{
				if(dragTower) return;
				var towerVO :TowerVO = VOManager.instance.getTowerVOByName(name);
				this.dragTower = new BaseTower(towerVO);
				this.dragTower.alpha = GameConst.MAP_OBJ_DRAG_ALPHA;
				this.towerAttackRange.showRange(towerVO.attRange);
				this.adsorber.visible = true;
				this.addChild(this.dragTower);
			}
		}
		/**
		 * 
		 * 更新地图上的视图和数据
		 */		
		public function update():void
		{
			if(this.dragTower)
			{
				this.towerAttackRange.x = stage.mouseX - 12;
				this.towerAttackRange.y = stage.mouseY - 12;
				var tx :Number = stage.mouseX - dragTower.width/2;
				var ty :Number = stage.mouseY - dragTower.height/2;
				this.dragTower.x = tx;
				this.dragTower.y = ty;
				var px :int = stage.mouseX/GameConst.TILE_WIDTH;
				var py :int = stage.mouseY/GameConst.TILE_HEIGHT;
				this.adsorber.x = px * GameConst.TILE_WIDTH;
				this.adsorber.y = py * GameConst.TILE_HEIGHT;
				this.dragTower.transform.colorTransform = this.curMapAry[py][px] == false ? new ColorTransform() : new ColorTransform(1,0,0,0.8,0,0,0,0.5);
				var level :int = GameModel.instance.curLevel;
				//寻路
				var startPoint :Point = GameConfig.m_start_point_ary[level];
				var endPoint :Point = GameConfig.m_end_point_ary[level];
				this.path = BuildMap.instance.findPath(startPoint,endPoint,this.curMapAry);

				
				//复制寻路路径
				this.tempX = px;
				this.tempY = py;
				this.contrastMapAry = GameUtil.instance.copyAry(this.curMapAry);
				this.contrastMapAry[py][px] = true;
				this.contrastPath = BuildMap.instance.findPath(startPoint,endPoint,this.contrastMapAry);
				//对比路径为空，不能建造
				if(!this.contrastPath)
				{
					this.path = null;
					this.pathLayer.graphics.clear();
					this.dragTower.transform.colorTransform = new ColorTransform(1,0,0,0.8,0,0,0,0.5);
					this.canBuild = false;
				}else
				{
					//如果两条路径相等
					var result :Boolean = GameUtil.instance.aryIsEquation(this.path,this.contrastPath);
					if(result)
					{
						drawPath();
						this.canBuild = true;
					}else    //如果不相等
					{
						this.path = this.contrastPath;
						drawPath();
						this.canBuild = true;
					}
				}
			}
			//更新防守塔状态
			this.towerList = GameModel.instance.towerList;
			if(this.towerList.length > 0)
			{
				for(var towerNum :int = 0; towerNum < towerList.length; towerNum++)
				{
					var tower :BaseTower = towerList[towerNum] as BaseTower;
					if(tower.isAlive)
					{
						tower.update();
					}else
					{
						towerList.splice(towerNum,1);
						this.removeItem(tower);
					}
				}
			}
//			//检查塔的鼠标onmouse状态
//			checkTowerOnMouse();
			
			//更新子弹的状态
			var bulletList :Vector.<Bullet> = GameModel.instance.bulletList;
			if(bulletList.length > 0)
			{
				for(var bulletNum :int = 0; bulletNum < bulletList.length; bulletNum++)
				{
					var bullet :Bullet = bulletList[bulletNum] as Bullet;
					if(bullet.isAlive)
					{
						bullet.update();
					}else
					{
						bulletList.splice(bulletNum,1);
						this.removeItem(bullet);
					}
				}
			}
			
			//更新怪物状态
			this.monsterList = GameModel.instance.monsterList;
			if(this.monsterList.length > 0)
			{
				
				for(var monsterNum :int = 0; monsterNum < monsterList.length; monsterNum++)
				{
					var monster :BaseMonster = monsterList[monsterNum] as BaseMonster;
					
					if(monster.isAlive)
					{
						if(!monster.isAdd2Map) return;
						monster.update();
					}else
					{
						//怪物死亡先将isAlive标记为false,输掉游戏再删掉，防止延迟加入怪物时删掉了还没加入的怪物
//						if(!monster.isAdd2Map) return;
//						monsterList.splice(monsterNum,1);
//						this.removeItem(monster);
					}
				}
			}
		}
		/**
		 * 开始迎战
		 * 
		 */		
		public function startBattle():void
		{
			if(GameModel.instance.battleNumber > GameConfig.monster_list.length) return;
			MonsterManager.instance.createMonster(GameModel.instance.battleNumber);
		}
		/**
		 * 取消操作 
		 * 
		 */		
		public function cancel():void
		{
			if(this.dragTower)
			{
				this.dragTower.transform.colorTransform = new ColorTransform();
				this.removeChild(this.dragTower);
				this.dragTower = null;
			}
			
			this.pathLayer.graphics.clear();
			if(this.towerAttackRange)
			{
				this.towerAttackRange.hideRange();
			}
			
			if(this.adsorber)
			{
				this.adsorber.visible = false;
			}
			
			if(this.theMouseOn)
			{
				this.theMouseOn = null;
			}
			this.isRemove = false;
			this.isMove = false;
			UIBottom.instance.btnRemove.filters = null;
			UIBottom.instance.btnMove.filters = null;
		}

		/**
		 * 增加对象到地图上 
		 * @param obj
		 * 
		 */		
		public function addItem(obj :*):void
		{
			if(!obj)  return;
			if(obj is BaseTower)  //防守塔
			{
				this.towerList = GameModel.instance.towerList;
				var curMapAry :Array = GameModel.instance.curMapAry;
				if(!this.isMove)
				{
					this.towerList.push(obj);
				}
				curMapAry[obj.mapY][obj.mapX] = true;
			}else if(obj is BaseMonster)  //怪物
			{
				var monster :BaseMonster = obj as BaseMonster;
				monster.isAdd2Map = true;
				this.addChild(monster);
			}else if (obj is Bullet)  //子弹
			{
				var bulletList :Vector.<Bullet> = GameModel.instance.bulletList;
				bulletList.push(obj);
				this.addChild(obj);
			}
		}
		
		/**
		 * 删除对象 
		 * @param obj
		 * 
		 */		
		public function removeItem(obj :*):void
		{
			if(!obj) return;
			
			
			if(obj is BaseTower)
			{
				var tower :BaseTower = obj as BaseTower;
				if(tower.bitmap.bitmapData)
				{
					tower.bitmap.bitmapData = null;
					tower.bitmap = null;
				}
				curMapAry[tower.mapY][tower.mapX] = false;
				this.removeChild(tower);
				tower = null;
				if(this.towerAttackRange)
				{
					this.towerAttackRange.hideRange();
				}
				if(this.isRemove)
				{
					this.dragTower = null;
					this.theMouseOn = null;
				}
			}else if(obj is BaseMonster)
			{
				//删除怪物和位图
				var monster :BaseMonster = obj as BaseMonster;
				for(var i :int = monster.curActionBMDAry.length - 1; i >= 0; i--)
				{
					(monster.curActionBMDAry[i] as BitmapData).dispose();
					monster.curActionBMDAry[i] = null;
					monster.curActionBMDAry.splice(i,1);
				}
				this.disposeBitmapData(monster.monsterVO.bmdDict[monster.monsterVO.dir_down * monster.monsterVO.ratio]);
				delete monster.monsterVO.bmdDict[monster.monsterVO.dir_down * monster.monsterVO.ratio];
				this.disposeBitmapData(monster.monsterVO.bmdDict[monster.monsterVO.dir_left * monster.monsterVO.ratio]);
				delete monster.monsterVO.bmdDict[monster.monsterVO.dir_left * monster.monsterVO.ratio];
				this.disposeBitmapData(monster.monsterVO.bmdDict[monster.monsterVO.dir_right * monster.monsterVO.ratio]);
				delete monster.monsterVO.bmdDict[monster.monsterVO.dir_right * monster.monsterVO.ratio];
				this.disposeBitmapData(monster.monsterVO.bmdDict[monster.monsterVO.dir_up * monster.monsterVO.ratio]);
				delete monster.monsterVO.bmdDict[monster.monsterVO.dir_up * monster.monsterVO.ratio];
				monster.monsterVO.bmdDict = null;
				if(monster.bitmap.bitmapData)
				{
					monster.bitmap.bitmapData.dispose();
					monster.bitmap.bitmapData = null;
					monster.bitmap = null;
				}
				if(monster.life)
				{
					monster.life.destroy();
					monster.life = null;
				}
				this.removeChild(monster);
				
				monster = null;
			}else if (obj is Bullet)
			{
				var bullet :Bullet = obj as Bullet;
				this.removeChild(bullet);
				bullet.bitmapData = null;
				bullet = null;
			}
		}
		
		public function removeTowerAttRange():void
		{
			if(this.towerAttackRange)
			{
				this.removeChild(this.towerAttackRange);
				this.towerAttackRange = null;
			}
		}
		/**
		 * 销毁 
		 * 
		 */		
		public function destroy():void
		{
			
		}
		
		/**
		 * 设置底图 
		 * @param name
		 * 
		 */		
		public function setMap(name :String):void
		{
			
			if(this.map)
			{
				this.removeChild(this.map);
				this.map = null;
			}
			var mc :MovieClip = McMannager.instance.getMCByName(name);
			if(mc)
			{
				this.map = mc;
				this.addChild(this.map);
			}
		}
		private function mouseHandler(event :MouseEvent):void
		{
			switch(event.type)
			{
				case MouseEvent.MOUSE_DOWN:
					break;
				case MouseEvent.MOUSE_UP:
					addTowerToMap();
					removeTower();
					moveTower();
					break;
				case MouseEvent.MOUSE_OVER:
					break;
				case MouseEvent.MOUSE_OUT:
					break;
				case MouseEvent.CLICK:
					break;
				case MouseEvent.MOUSE_MOVE:
					//检查塔的鼠标onmouse状态
					checkTowerOnMouse();
//					UITooltip.instance.checkIsMouseOn();
					break;
				default :
					break;
			}
		}
		
		/**
		 * 增加防守塔到地图上
		 * 
		 */		
		private function addTowerToMap():void
		{
			if(!this.dragTower) return;
			if(!this.canBuild) return;
			var mapX :int = int(stage.mouseX/GameConst.TILE_WIDTH);
			var mapY :int = int(stage.mouseY/GameConst.TILE_HEIGHT);
			if(this.curMapAry[mapY][mapX])
			{
				return;
			}
			if(GameModel.instance.curGameGold < this.dragTower.towerVO.price)
			{
				this.cancel();
				return;
			}
			if(!this.isMove)
			UITop.instance.updateGold(this.dragTower.towerVO.price,false);
			this.towerAttackRange.hideRange();
			this.adsorber.visible = false;
			this.dragTower.x = int(stage.mouseX/GameConst.TILE_WIDTH) * GameConst.TILE_WIDTH + (GameConst.TILE_WIDTH - GameConst.TOWER_WIDTH)/2;
			this.dragTower.y = int(stage.mouseY/GameConst.TILE_HEIGHT) * GameConst.TILE_HEIGHT + (GameConst.TILE_HEIGHT - GameConst.TOWER_HEIGHT)/2;
			this.dragTower.mapX = mapX;
			this.dragTower.mapY = mapY;
			this.dragTower.bulletStartPoint.x = this.dragTower.x + 25;
			this.dragTower.bulletStartPoint.y = this.dragTower.y;
			this.dragTower.transform.colorTransform = new ColorTransform();
			this.dragTower.alpha = 1;
			this.dragTower.showBaseRect();
			this.pathLayer.graphics.clear();
			this.addItem(this.dragTower);
			this.dragTower = null;
		}
		/**
		 * 根据寻路得到的数组画出路径 
		 * 
		 */		
		private function drawPath():void
		{
			if(this.path && this.path.length > 0)
			{
				
				var len :int = this.path.length;
				var p :Point = this.path[0];
				var tx :int = p.x * GameConst.TILE_WIDTH + GameConst.TILE_WIDTH/2;
				var ty :int = p.y * GameConst.TILE_HEIGHT + GameConst.TILE_HEIGHT/2;
				this.pathLayer.graphics.clear();
				this.pathLayer.graphics.lineStyle(2,0xffff00);
				this.pathLayer.graphics.moveTo(tx,ty);
				for(var i :int = 1; i < len; i++)
				{
					p = this.path[i];
					tx = p.x * GameConst.TILE_WIDTH + GameConst.TILE_WIDTH/2;
					ty = p.y * GameConst.TILE_HEIGHT + GameConst.TILE_HEIGHT/2;
					this.pathLayer.graphics.lineTo(tx,ty);
				}
			}else
			{
				this.pathLayer.graphics.clear();
			}
		}
		/**
		 * 检查鼠标是否在防守塔上 
		 * 
		 */		
		private function checkTowerOnMouse():void
		{
			if(this.towerList.length > 0)
			{
				for(var towerNum :int = 0; towerNum < towerList.length; towerNum++)
				{
					var tower :BaseTower = towerList[towerNum] as BaseTower;
					if(tower.isAlive)
					{
						if(tower.isMouseOn() && !this.dragTower)
						{
							this.theMouseOn = tower;
							break;
						}else
						{
							this.theMouseOn = null;
						}
					}
				}
				
				if(this.towerAttackRange)
				{
					if(this.theMouseOn)
					{
						this.towerAttackRange.showRange(theMouseOn.towerVO.attRange,theMouseOn.x + 25,theMouseOn.y + 25);
//						this.addChildAt(this.towerAttackRange,this.numChildren - 1);
					}else
					{
						if(!this.dragTower)
						{
							this.towerAttackRange.hideRange();
						}
					}
				}
				
			}
		}
		/**
		 * 重置地图数据 
		 * 
		 */		
		public function clear():void
		{
		}

		public static function get instance():UIMap
		{
			if(_instance == null)
			{
				_instance = new UIMap();
			}
			return _instance;
		}
		
		/**
		 * 销毁位图 
		 * @param list
		 * 
		 */		
		private function disposeBitmapData(list :Vector.<BitmapData>):void
		{
			for(var i :int = list.length - 1; i >= 0; i--)
			{
				var bmd :BitmapData = list[i] as BitmapData;
				bmd.dispose();
				bmd = null;
				list.splice(i,1);
			}
			
			if(list.length == 0)
			{
				list = null;
			}
		}
		/**
		 * 拆除塔 
		 * 
		 */		
		private function removeTower():void
		{
			
			if(this.isRemove)
			{
				
				if(this.theMouseOn)
				{
					this.theMouseOn.isAlive = false;
					trace("移除");
				}
			}
		}
		/**
		 * 移動塔 
		 * 
		 */		
		private function moveTower():void
		{
			if(this.isMove)
			{
				if(this.theMouseOn)
				{
					this.curMapAry[this.theMouseOn.mapY][this.theMouseOn.mapX] = false;
					this.dragTower = this.theMouseOn;
					trace("移动");
				}
			}
		}
		
		private function checkTooltipMouseOn():void
		{
			
		}

	}
}